//****************************************************************
//* Copyright (c) 2008 Ford Motor Company. All Rights Reserved.
//*
//* $$Workfile:   CostStructureFindAction.java  $$
//* $$Revision:   1.2  $$
//* $$Author:   TMALDON4  $$
//* $$Date:   Feb 26 2009 07:30:46  $$
//*
//*****************************************************************
package ar.com.ford.it.fullEconomics.view.action;

import java.util.Collection;
import java.util.LinkedList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.facade.CommodityFacade;
import ar.com.ford.it.fullEconomics.facade.CostStructureFacade;
import ar.com.ford.it.fullEconomics.facade.FullEconomicsFacade;
import ar.com.ford.it.fullEconomics.facade.SupplierFacade;
import ar.com.ford.it.fullEconomics.facade.UserFacade;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesc03Subcoststr;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesf01Fulleconom;
import ar.com.ford.it.fullEconomics.struct.CostStructureFindStruct;
import ar.com.ford.it.fullEconomics.struct.OptionCombo;
import ar.com.ford.it.fullEconomics.view.form.CostStructureFindForm;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.facade.FacadeProvider;
import ar.com.ford.it.webengine.struts.AbstractBaseAction;
import ar.com.ford.it.webengine.struts.FordActionMapping;
import ar.com.ford.it.webengine.websession.WebSession;

public class CostStructureFindAction extends AbstractBaseAction {

    /**
     * Setea el error que indica que la Cost Structure no puede ser aprobada
     * 
     * @param request
     */
    private void setErrorCostStructureCannotBeApproved(
                                                       HttpServletRequest request) {
        ActionMessages am = new ActionMessages();

        am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                "costStructure.find.error.approve.sameUser"));
        saveErrors(request, am);
    }

    /**
     * Setea el error que informa que la estructura de costos no puede ser
     * aprobada dado que alguno de sus items no esta aprobado.
     * 
     * @param request
     */
    private void setErrorNotAllSubCostStrItemsAreApproved(
                                                          HttpServletRequest request) {
        ActionMessages am = new ActionMessages();

        am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                "costStructure.find.error.approve.itemsNotApproved"));
        saveErrors(request, am);
    }

    /**
     * 
     * @return Coleccion de posibles estados de Cost Structure
     */
    private Collection getComboStatus(HttpServletRequest request) {
        LinkedList<OptionCombo> list = new LinkedList<OptionCombo>();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);

        list.add(new OptionCombo("Draft", resources.getMessage("label.draft")));
        list.add(new OptionCombo("Proposed", resources
                .getMessage("label.proposed")));
        list.add(new OptionCombo("Approved", resources
                .getMessage("label.approved")));

        return list;
    }


    /**
     * 
     */
    public ActionForward initPage(FordActionMapping mapping,
                                  ActionForm actionForm,
                                  HttpServletRequest request,
                                  HttpServletResponse response,
                                  WebSession webSession, ActionMessages msgs,
                                  ActionMessages warns, ActionMessages errorMsgs) {
        CostStructureFindForm form = (CostStructureFindForm) actionForm;
        CostStructureFacade csFacade = (CostStructureFacade) FacadeProvider
                .getFacade(request, CostStructureFacade.class);
        SupplierFacade supplierFacade = (SupplierFacade) FacadeProvider
                .getFacade(request, SupplierFacade.class);
        CommodityFacade commodityFacade = (CommodityFacade) FacadeProvider
                .getFacade(request, CommodityFacade.class);
        UserFacade userFacade = (UserFacade) FacadeProvider.getFacade(request,
                UserFacade.class);
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();

        try {
            form.setStatusCol(this.getComboStatus(request));
            request.getSession().setAttribute("statusCol", form.getStatusCol());
            form.setSupplierTypeCol(supplierFacade.getComboSupplierType());
            request.getSession().setAttribute("supplierTypeCol",
                    form.getSupplierTypeCol());
            form.setPartClassesCol(commodityFacade.getPartClases());
            request.getSession().setAttribute("partClassesCol",
                    form.getPartClassesCol());
            form.setCommoditiesCol(commodityFacade.findCommodities("", "", user
                    .getTeesg01Plant()));
            request.getSession().setAttribute("commoditiesCol",
                    form.getCommoditiesCol());
            form.setUserActionsTypesCol(userFacade.getUserActionTypes());
            request.getSession().setAttribute("userActionsTypesCol",
                    form.getUserActionsTypesCol());
            form.setDateTypesCol(csFacade.getComboDateTypes());
            request.getSession().setAttribute("dateTypesCol",
                    form.getDateTypesCol());
            form.resetForm();
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward findCostStructure(FordActionMapping mapping,
                                           ActionForm actionForm,
                                           HttpServletRequest request,
                                           HttpServletResponse response,
                                           WebSession webSession,
                                           ActionMessages msgs,
                                           ActionMessages warns,
                                           ActionMessages errorMsgs) {
        CostStructureFindForm form = (CostStructureFindForm) actionForm;
        CostStructureFacade facade = (CostStructureFacade) FacadeProvider
                .getFacade(request, CostStructureFacade.class);
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        CostStructureFindStruct parameters = form.getFindParameters(user);

        try {
            form.setCostStructureVersions(facade
                    .findCostStructureVersions(parameters));
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward editCostStructure(FordActionMapping mapping,
                                           ActionForm actionForm,
                                           HttpServletRequest request,
                                           HttpServletResponse response,
                                           WebSession webSession,
                                           ActionMessages msgs,
                                           ActionMessages warns,
                                           ActionMessages errorMsgs) {
        CostStructureFindForm form = (CostStructureFindForm) actionForm;

        request.setAttribute("costStrVersionSelected", form
                .getCsVersionSelected());
        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward costStructureNewVersion(FordActionMapping mapping,
                                                 ActionForm actionForm,
                                                 HttpServletRequest request,
                                                 HttpServletResponse response,
                                                 WebSession webSession,
                                                 ActionMessages msgs,
                                                 ActionMessages warns,
                                                 ActionMessages errorMsgs) {
        CostStructureFindForm form = (CostStructureFindForm) actionForm;

        request.setAttribute("costStrVersionSelected", form
                .getCsVersionSelected());
        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward costStructureCopyTo(FordActionMapping mapping,
                                             ActionForm actionForm,
                                             HttpServletRequest request,
                                             HttpServletResponse response,
                                             WebSession webSession,
                                             ActionMessages msgs,
                                             ActionMessages warns,
                                             ActionMessages errorMsgs) {
        CostStructureFindForm form = (CostStructureFindForm) actionForm;

        request.setAttribute("costStrVersionSelected", form
                .getCsVersionSelected());
        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward costStructureHeader(FordActionMapping mapping,
                                             ActionForm actionForm,
                                             HttpServletRequest request,
                                             HttpServletResponse response,
                                             WebSession webSession,
                                             ActionMessages msgs,
                                             ActionMessages warns,
                                             ActionMessages errorMsgs) {
        CostStructureFindForm form = (CostStructureFindForm) actionForm;

        request.setAttribute("costStrVersionSelected", form
                .getCsVersionSelected());
        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward costStructureDelete(FordActionMapping mapping,
                                             ActionForm actionForm,
                                             HttpServletRequest request,
                                             HttpServletResponse response,
                                             WebSession webSession,
                                             ActionMessages msgs,
                                             ActionMessages warns,
                                             ActionMessages errorMsgs) {
        CostStructureFindForm form = (CostStructureFindForm) actionForm;
        CostStructureFacade costStructureFacade = (CostStructureFacade) FacadeProvider
                .getFacade(request, CostStructureFacade.class);
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        FullEconomicsFacade fullEconomicFacade = (FullEconomicsFacade) FacadeProvider
                .getFacade(request, FullEconomicsFacade.class);
        Teesf01Fulleconom fullEconomics = null;

        try {
            if ("deleteCostStrVersion".equalsIgnoreCase(form.getSection())) {
                fullEconomics = fullEconomicFacade
                        .findFullEconomicsByCostStrVersion(form
                                .getCsVersionSelected());
                if (fullEconomics == null) {
                    costStructureFacade.deleteSubCostStrVersion(user, form
                            .getCsVersionSelected());
                } else {
                    form.setSection("confirmDeleteCostStrVersion");
                }
            } else if ("deleteCostStrVersionConfirmed".equalsIgnoreCase(form
                    .getSection())) {
                costStructureFacade.deleteSubCostStrVersion(user, form
                        .getCsVersionSelected());
            }
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }

        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward proposeCostStrVersion(FordActionMapping mapping,
                                               ActionForm actionForm,
                                               HttpServletRequest request,
                                               HttpServletResponse response,
                                               WebSession webSession,
                                               ActionMessages msgs,
                                               ActionMessages warns,
                                               ActionMessages errorMsgs) {
        ActionMessages am = new ActionMessages();
        CostStructureFindForm form = (CostStructureFindForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        CostStructureFacade facade = (CostStructureFacade) FacadeProvider
                .getFacade(request, CostStructureFacade.class);

        try {
            Teesc03Subcoststr incompleteSubCostStr = facade
                    .getIncompleteSubCostStr(form.getCsVersionSelected()
                            .getTeesc03Subcoststr());
            if (incompleteSubCostStr != null) {
                am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                        "costStructure.def.error.subCostStrIncomplete",
                        incompleteSubCostStr.getEesc03SubcstNameN()));
                saveErrors(request, am);
            } else {
                if (facade.costStructureCanBeProposed(form
                        .getCsVersionSelected())) {
                    facade.proposeCostStructure(form.getCsVersionSelected(),
                            user);
                }
            }
        } catch (FullEconomicsException e) {

            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }

        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward approveCostStrVersion(FordActionMapping mapping,
                                               ActionForm actionForm,
                                               HttpServletRequest request,
                                               HttpServletResponse response,
                                               WebSession webSession,
                                               ActionMessages msgs,
                                               ActionMessages warns,
                                               ActionMessages errorMsgs) {
        CostStructureFindForm form = (CostStructureFindForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        CostStructureFacade facade = (CostStructureFacade) FacadeProvider
                .getFacade(request, CostStructureFacade.class);

        try {
            if (facade.costStructureCanBeApproved(form.getCsVersionSelected(),
                    user)) {
                if (facade.checkIfallItemsAreApproved(form
                        .getCsVersionSelected())) {
                    facade.approveCostStructure(form.getCsVersionSelected(),
                            user);
                } else {
                    this.setErrorNotAllSubCostStrItemsAreApproved(request);
                }
            } else {
                this.setErrorCostStructureCannotBeApproved(request);
            }
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward cleanCostStructureFind(FordActionMapping mapping,
                                                ActionForm actionForm,
                                                HttpServletRequest request,
                                                HttpServletResponse response,
                                                WebSession webSession,
                                                ActionMessages msgs,
                                                ActionMessages warns,
                                                ActionMessages errorMsgs) {
        CostStructureFindForm form = (CostStructureFindForm) actionForm;
        form.cleanFindFields();
        return mapping.findForward("success");
    }

}
